package com.example.shorg.convert;

import com.example.shorg.dataobject.OrderDetail;
import com.example.shorg.dto.OrderDTO;
import com.example.shorg.enums.ResultEnum;
import com.example.shorg.exception.ShorgException;
import com.example.shorg.form.OrderForm;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 转换数据
 * */
@Slf4j
public class OrderForm2OrderDTOConverter {

    /***
     * 将form的数据转换成dto的数据
     * */
    public static OrderDTO convert(OrderForm orderForm){
        Gson gson = new Gson();
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setBuyerName(orderForm.getName());
        orderDTO.setBuyerPhone(orderForm.getPhone());
        orderDTO.setBuyerAddress(orderForm.getAddress());
        orderDTO.setBuyerOpenid(orderForm.getOpenid());
        List<OrderDetail> orderDetailList = new ArrayList<OrderDetail>();
        try {
            orderDetailList = gson.fromJson(orderForm.getItems(), new TypeToken<List<OrderDetail>>() {
            }.getType());
        }catch (Exception e){
            log.error("对象转换错误, string={}", orderForm.getItems());
            throw new ShorgException(ResultEnum.PARAM_ERROR);
        }
        orderDTO.setOrderDetailList(orderDetailList);
        return orderDTO;
    }

}
